﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_Report_ImportExport : System.Web.UI.UserControl
{
    DBDataContext db;
    DatabaseHelper helper;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["Username"] != null)
            {
                loadProvince();
                Utils.loadProductToComboSearch(cbProduct, 1, "");
                gvData.DataSource = new DataTable();
                gvData.DataBind();

                gv_detail.DataSource = new DataTable();
                gv_detail.DataBind();
            }
        }
    }
    private void loadProvince()
    {
        try
        {
            //Load tinh thanh 
            int ProvinceID = Session["ProvinceID"] == null ? 0 : int.Parse(Session["ProvinceID"].ToString());
            int isProvinceAll = (ProvinceID == 0 ? 1 : 0);
            Utils.loadLocationSearch(cboProvince, 0, isProvinceAll, ProvinceID);//Search
            loadShop(ProvinceID);


        }
        catch (Exception ex)
        {
            ControlUtil.LogError("ImportExport Page-LoadProvince:" + ex.Message);
        }
    }
    private DataTable loadData(string ListShopID = "", int ProvinceID = 0, string strTypeSearch = "", string StartDate = "", string EndDate = "", int PageSize = 10000, int iProductID = -1)
    {
        try
            {
            int PageNumber = gvData.CurrentPageIndex + 1;
            //int PageSize = gvData.PageSize;

            helper = new DatabaseHelper();

            System.Data.Common.DbParameter paramProvinceID = helper.Parameter;
            paramProvinceID.ParameterName = "ProvinceID";
            paramProvinceID.DbType = DbType.Int32;
            paramProvinceID.Value = ProvinceID;
            helper.AddParameter(paramProvinceID);

            System.Data.Common.DbParameter paramFromShopID = helper.Parameter;
            paramFromShopID.ParameterName = "ListShopID";
            paramFromShopID.DbType = DbType.String;
            paramFromShopID.Value = ListShopID;
            helper.AddParameter(paramFromShopID);

            System.Data.Common.DbParameter paramType = helper.Parameter;
            paramType.ParameterName = "ProductType";
            paramType.DbType = DbType.String;
            paramType.Value = strTypeSearch;
            helper.AddParameter(paramType);

            System.Data.Common.DbParameter paramProductID = helper.Parameter;
            paramProductID.ParameterName = "ProductID";
            paramProductID.DbType = DbType.Int32;
            paramProductID.Value = iProductID;
            helper.AddParameter(paramProductID);

            System.Data.Common.DbParameter paramStartDate = helper.Parameter;
            paramStartDate.ParameterName = "StartDate";
            paramStartDate.DbType = DbType.String;
            paramStartDate.Value = StartDate;
            helper.AddParameter(paramStartDate);

            System.Data.Common.DbParameter paramEndDate = helper.Parameter;
            paramEndDate.ParameterName = "EndDate";
            paramEndDate.DbType = DbType.String;
            paramEndDate.Value = EndDate;
            helper.AddParameter(paramEndDate);

            System.Data.Common.DbParameter paramPageNumber = helper.Parameter;
            paramPageNumber.ParameterName = "PageNumber";
            paramPageNumber.DbType = DbType.Int32;
            paramPageNumber.Value = PageNumber;
            helper.AddParameter(paramPageNumber);

            System.Data.Common.DbParameter paramPageSize = helper.Parameter;
            paramPageSize.ParameterName = "PageSize";
            paramPageSize.DbType = DbType.Int32;
            paramPageSize.Value = PageSize;
            helper.AddParameter(paramPageSize);
            DataTable dt = helper.ExecuteDataTable("Report_ImportExport", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
           
            return dt;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("ImportExport Page-loadData:" + ex.Message);
            return new DataTable();
        }
    }
    private DataTable loadDataDetail(string ListShopID = "", int ProvinceID = 0, string strTypeSearch = "", string StartDate = "", string EndDate = "", string strType="I", string strProductID = "-1", int PageSize = 10000)
    {
        try
        {
            int PageNumber = gv_detail.CurrentPageIndex + 1;
            //int PageSize = gvData.PageSize;

            helper = new DatabaseHelper();

            System.Data.Common.DbParameter paramProvinceID = helper.Parameter;
            paramProvinceID.ParameterName = "ProvinceID";
            paramProvinceID.DbType = DbType.Int32;
            paramProvinceID.Value = ProvinceID;
            helper.AddParameter(paramProvinceID);

            System.Data.Common.DbParameter paramFromShopID = helper.Parameter;
            paramFromShopID.ParameterName = "ListShopID";
            paramFromShopID.DbType = DbType.String;
            paramFromShopID.Value = ListShopID;
            helper.AddParameter(paramFromShopID);

            System.Data.Common.DbParameter paramType = helper.Parameter;
            paramType.ParameterName = "Type";
            paramType.DbType = DbType.String;
            paramType.Value = strType;
            helper.AddParameter(paramType);

            System.Data.Common.DbParameter paramProductID = helper.Parameter;
            paramProductID.ParameterName = "ProductID";
            paramProductID.DbType = DbType.Int32;
            paramProductID.Value = Convert.ToInt32(strProductID);
            helper.AddParameter(paramProductID);

            System.Data.Common.DbParameter paramProductType = helper.Parameter;
            paramProductType.ParameterName = "ProductType";
            paramProductType.DbType = DbType.String;
            paramProductType.Value = strTypeSearch;
            helper.AddParameter(paramProductType);

            System.Data.Common.DbParameter paramStartDate = helper.Parameter;
            paramStartDate.ParameterName = "StartDate";
            paramStartDate.DbType = DbType.String;
            paramStartDate.Value = StartDate;
            helper.AddParameter(paramStartDate);

            System.Data.Common.DbParameter paramEndDate = helper.Parameter;
            paramEndDate.ParameterName = "EndDate";
            paramEndDate.DbType = DbType.String;
            paramEndDate.Value = EndDate;
            helper.AddParameter(paramEndDate);

            System.Data.Common.DbParameter paramPageNumber = helper.Parameter;
            paramPageNumber.ParameterName = "PageNumber";
            paramPageNumber.DbType = DbType.Int32;
            paramPageNumber.Value = PageNumber;
            helper.AddParameter(paramPageNumber);

            System.Data.Common.DbParameter paramPageSize = helper.Parameter;
            paramPageSize.ParameterName = "PageSize";
            paramPageSize.DbType = DbType.Int32;
            paramPageSize.Value = PageSize;
            helper.AddParameter(paramPageSize);
            DataTable dt = helper.ExecuteDataTable("Report_ImportExportDetail", CommandType.StoredProcedure, ConnectionState.CloseOnExit);

            return dt;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("ImportExport Page-loadDataDetail:" + ex.Message);
            return new DataTable();
        }
    }
    private void loadShop(int ProvinceID = -1)
    {
        try
        {
            //load Shop
            int ShopID = Session["ShopID"] == null ? 0 : int.Parse(Session["ShopID"].ToString());
            int isShopAll = (ShopID == 0 ? 1 : 0);
            Utils.loadShopToRadListBox(cbShop, ProvinceID, ShopID, "");
            IList<RadListBoxItem> collection = cbShop.Items;
            if (collection.Count == 1)
            {
                collection[0].Checked = true;
                cbShop.Enabled = false;
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("ImportExport Page-loadShop:" + ex.Message);
        }
    }
    private void getDataSearch()
    {
        try
        {
            IList<RadListBoxItem> collection = cbShop.CheckedItems;
            string strListShopID = "";

            for (int i = 0; i < collection.Count; i++)
            {
                strListShopID = strListShopID + Convert.ToInt32(collection[i].Value) + ",";
            }
            if (strListShopID != "")
                strListShopID = strListShopID.Substring(0, strListShopID.Length - 1);
            string strProvinceID = cboProvince.SelectedValue;
            string strStartDate = Utils.KillChars(this.rtpFromDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpFromDateSearch.SelectedDate));
            string strEndDate = Utils.KillChars(this.rtpToDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpToDateSearch.SelectedDate));
            string strTypeSearch = Utils.KillChars(cbTypeSearch.SelectedValue.Trim().ToString());
            int iProductID = Convert.ToInt32(Utils.KillChars(cbProduct.SelectedValue.Trim().ToString() == "" ? "-1" : cbProduct.SelectedValue.Trim().ToString()));
            DataTable dt = loadData(strListShopID, Convert.ToInt32(strProvinceID == "0" ? "-1" : strProvinceID), strTypeSearch, strStartDate, strEndDate, gvData.PageSize, iProductID);
            if (dt.Rows.Count > 0)
            {
                gvData.Height = 250;
                gvData.ClientSettings.Scrolling.AllowScroll = true;
                gvData.ClientSettings.Scrolling.UseStaticHeaders = true;
                gvData.VirtualItemCount = Convert.ToInt32(dt.Rows[0]["TotalRows"]);
                div_TotalRows.InnerText = "Kết quả tìm kiếm: " + String.Format("{0:N0}", dt.Rows[0]["TotalRows"]);
                gvData.DataSource = dt;
            }
            else
            {
                gvData.DataSource = new DataTable();
                div_TotalRows.InnerText = "Kết quả tìm kiếm: 0";
            }

            //gvData.DataBind();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("ImportExport Page-getDataSearch:" + ex.Message);
        }
    }
    
    protected void cboProvince_SelectedIndexChanged(object sender, EventArgs e)
    {
        int ProvinceID = int.Parse(this.cboProvince.SelectedValue == "" ? "0" : this.cboProvince.SelectedValue);
        Utils.loadShopToRadListBox(cbShop, ProvinceID, 0, "");
        IList<RadListBoxItem> collection = cbShop.Items;
        if (collection.Count == 1)
        {
            collection[0].Checked = true;
            cbShop.Enabled = false;
        }
        else cbShop.Enabled = true;
    }
    protected void cbType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (cbTypeSearch.SelectedValue == "R")
        {
            Utils.loadProductToComboSearch(cbProduct, 1, "R");
        }
        if (cbTypeSearch.SelectedValue == "P")
        {
            Utils.loadProductToComboSearch(cbProduct, 1, "P");
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                IList<RadListBoxItem> collection = cbShop.CheckedItems;
                if (collection.Count <= 0)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn cửa hàng!");
                    cbShop.Focus();
                    return;
                }
               getDataSearch();
               gvData.DataBind();
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("ImportExport Page-btnSearch_Click:" + ex.Message);
            }
        }
    }
    protected void gvData_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        try
        {
            ////Ham phan trang: Paging
            //(sender as RadGrid).DataSource = loadData();
            IList<RadListBoxItem> collection = cbShop.CheckedItems;
            if (collection.Count > 0)
                getDataSearch();
            //gvData.Rebind();
           
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("StockReturn Page-gvData_NeedDataSource:" + ex.Message);
        }
    }
    protected void gvData_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                string commandName = e.CommandName;
                string ListParam = e.CommandArgument.ToString();
                ViewState["ListParam"] = ListParam;
                helper = new DatabaseHelper();
                if (commandName == "ItemDetail")
                {
                    try
                    {
                        RadPageView2.Selected = true;
                        TabStrip1.SelectedIndex = 1;
                        //IList<RadListBoxItem> collection = cbShop.CheckedItems;
                        string strListShopID = string.Empty;
                        string strType = string.Empty;
                        string strProductID = string.Empty;
                        //for (int i = 0; i < collection.Count; i++)
                        //{
                        //    strListShopID = strListShopID + Convert.ToInt32(collection[i].Value) + ",";
                        //}
                        //if (strListShopID != "")
                        //    strListShopID = strListShopID.Substring(0, strListShopID.Length - 1);
                        string[] arr = ListParam.Split(';');
                        strType = arr[0];
                        strListShopID = arr[1];
                        strProductID = arr[2];
                        string strProvinceID = cboProvince.SelectedValue;
                        string strStartDate = Utils.KillChars(this.rtpFromDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpFromDateSearch.SelectedDate));
                        string strEndDate = Utils.KillChars(this.rtpToDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpToDateSearch.SelectedDate));
                        string strTypeSearch = Utils.KillChars(cbTypeSearch.SelectedValue.Trim().ToString());
                        DataTable dt = loadDataDetail(strListShopID, Convert.ToInt32(strProvinceID == "0" ? "-1" : strProvinceID), strTypeSearch, strStartDate, strEndDate, strType, strProductID, gv_detail.PageSize);
                        if (dt.Rows.Count > 0)
                        {
                            gv_detail.DataSource = dt;
                            gv_detail.DataBind();
                            gv_detail.VirtualItemCount = Convert.ToInt32(dt.Rows[0]["TotalRows"]);
                            div_DetailTotal.InnerText = "Kết quả tìm kiếm: " + String.Format("{0:N0}", dt.Rows[0]["TotalRows"]);
                        }
                        else
                        {
                            gv_detail.DataSource = new DataTable();
                            div_DetailTotal.InnerText = "Kết quả tìm kiếm: 0";
                        }
                        gv_detail.DataBind();
                    }
                    catch (Exception ex)
                    {
                        ControlUtil.LogError("ImportExport Page-gvData_ItemCommand-ItemDetail:" + ListParam + ":" + ex.Message);
                    }
                }
                
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("ImportExport Page-gvData_ItemCommand:" + ex.Message);
            }
        }
    }
    protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        IList<RadListBoxItem> collection = cbShop.CheckedItems;
        string strListShopID = "";

        for (int i = 0; i < collection.Count; i++)
        {
            strListShopID = strListShopID + Convert.ToInt32(collection[i].Value) + ",";
        }
        if (strListShopID != "")
            strListShopID = strListShopID.Substring(0, strListShopID.Length - 1);
        string strProvinceID = cboProvince.SelectedValue;
        string strStartDate = Utils.KillChars(this.rtpFromDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpFromDateSearch.SelectedDate));
        string strEndDate = Utils.KillChars(this.rtpToDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpToDateSearch.SelectedDate));
        string strTypeSearch = Utils.KillChars(cbTypeSearch.SelectedValue.Trim().ToString());
        DataTable tblresult = loadData(strListShopID, Convert.ToInt32(strProvinceID == "0" ? "-1" : strProvinceID),strTypeSearch, strStartDate, strEndDate, gvData.VirtualItemCount);
        
        if (tblresult.Rows.Count > 0)
        {
            ExcelUtil.ExportDataTableToExcel2007FromRadGrid(tblresult, gvData, "tinhhinhxuatnhapkho");
        }
        else
        {
            JavascriptUtil.LoadMessage(Page, false, "Không có dữ liệu xuất Excel !!!");
        }
    }
    protected void gvDetail_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        try
        {
            ////Ham phan trang: Paging
            if (RadPageView2.Selected)
            {
                TabStrip1.SelectedIndex = 1;
                string strListShopID = string.Empty;
                string strType = string.Empty;
                string strProductID = string.Empty;
                //for (int i = 0; i < collection.Count; i++)
                //{
                //    strListShopID = strListShopID + Convert.ToInt32(collection[i].Value) + ",";
                //}
                //if (strListShopID != "")
                //    strListShopID = strListShopID.Substring(0, strListShopID.Length - 1);

                if (ViewState["ListParam"] != null)
                {
                    string[] arr = ViewState["ListParam"].ToString().Split(';');
                    strType = arr[0];
                    strListShopID = arr[1];
                    strProductID = arr[2];
                    string strProvinceID = cboProvince.SelectedValue;
                    string strStartDate = Utils.KillChars(this.rtpFromDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpFromDateSearch.SelectedDate));
                    string strEndDate = Utils.KillChars(this.rtpToDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpToDateSearch.SelectedDate));
                    string strTypeSearch = Utils.KillChars(cbTypeSearch.SelectedValue.Trim().ToString());
                    DataTable dt = loadDataDetail(strListShopID, Convert.ToInt32(strProvinceID == "0" ? "-1" : strProvinceID), strTypeSearch, strStartDate, strEndDate, strType, strProductID, gv_detail.PageSize);
                    if (dt.Rows.Count > 0)
                    {
                        gv_detail.DataSource = dt;
                        //gv_detail.DataBind();
                        div_DetailTotal.InnerText = "Kết quả tìm kiếm: " + String.Format("{0:N0}", dt.Rows[0]["TotalRows"]);
                    }
                    else
                    {
                        gv_detail.DataSource = new DataTable();
                        div_DetailTotal.InnerText = "Kết quả tìm kiếm: 0";
                    }
                }
                else
                {
                    gv_detail.DataSource = new DataTable();
                }
            }
            else
            {
                gv_detail.DataSource = new DataTable();
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("ImportExport Page-gv_detail_NeedDataSource:" + ex.Message);
        }
    }
    protected void btnExportDetail_Click(object sender, EventArgs e)
    {
        RadPageView2.Selected = true;
        TabStrip1.SelectedIndex = 1;
        //IList<RadListBoxItem> collection = cbShop.CheckedItems;
        string strListShopID = string.Empty;
        string strType = string.Empty;
        string strProductID = string.Empty;
        //for (int i = 0; i < collection.Count; i++)
        //{
        //    strListShopID = strListShopID + Convert.ToInt32(collection[i].Value) + ",";
        //}
        //if (strListShopID != "")
        //    strListShopID = strListShopID.Substring(0, strListShopID.Length - 1);
        if (ViewState["ListParam"] != null)
        {
            string[] arr = ViewState["ListParam"].ToString().Split(';');
            strType = arr[0];
            strListShopID = arr[1];
            strProductID = arr[2];
            string strProvinceID = cboProvince.SelectedValue;
            string strStartDate = Utils.KillChars(this.rtpFromDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpFromDateSearch.SelectedDate));
            string strEndDate = Utils.KillChars(this.rtpToDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpToDateSearch.SelectedDate));
            string strTypeSearch = Utils.KillChars(cbTypeSearch.SelectedValue.Trim().ToString());
            DataTable dt = loadDataDetail(strListShopID, Convert.ToInt32(strProvinceID == "0" ? "-1" : strProvinceID), strTypeSearch, strStartDate, strEndDate, strType, strProductID, gv_detail.VirtualItemCount);
            if (dt.Rows.Count > 0)
            {
                ExcelUtil.ExportDataTableToExcel2007FromRadGrid(dt, gv_detail, "tinhhinhxuatnhapkhochitiet");
            }
            else
            {
                JavascriptUtil.LoadMessage(Page, false, "Không có dữ liệu xuất Excel !!!");
            }
        }
        else
        {
            JavascriptUtil.LoadMessage(Page, false, "Không có dữ liệu xuất Excel !!!");
        }
    }
}